package cn.tedu.myvrd.controller;

import cn.tedu.myvrd.entity.User;
import cn.tedu.myvrd.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;

    @RequestMapping("/login")
    public boolean login(User user, String rem,
                         HttpServletResponse response, HttpSession session){
        System.out.println("user = " + user + ",rem =" +rem);
        //查询用户名对应的用户对象
        User u = mapper.login(user);
        //判断是否存在
        if (u!=null){
            //判断如果输入的和查询的密码一致 则登录成功 否则登录失败
            if (u.getPassword().equals(user.getPassword())){
                //判断需要记住用户名和密码
                if (rem!=null) {
                    //把用户名和密码保存到Cookie里面
                    Cookie c1 = new Cookie("username", user.getUsername());
                    Cookie c2 = new Cookie("password", user.getPassword());
                    //设置保存时间 单位秒
                    c1.setMaxAge(60 * 60 * 24 * 30);
                    c2.setMaxAge(60 * 60 * 24 * 30);
                    //通过响应对象response把cookie发到客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                //通过session记住登录状态
                //把登录成功的user对象保存到session中用于表示登录成功
                session.setAttribute("user",u);

                return true;
            }
        }

        return false;
    }


    @RequestMapping("/checkrem")
    public User checkrem(HttpServletRequest request){
        User user = new User();
        //取出所有Cookie
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie c: cookies){
                //判断如果cookie的名字为用户名 则把值保存到user对象中
                if (c.getName().equals("username")){
                    user.setUsername(c.getValue());
                }
                if (c.getName().equals("password")){
                    user.setPassword(c.getValue());
                }
            }
        }
        return user;
    }

    @RequestMapping("/checklogin")
    public boolean checkLogin(HttpSession session){

        System.out.println("user = " + session.getAttribute("user"));
        if (session.getAttribute("user")==null){
            return false;
        }
        return true;
        //return session.getAttribute("user")!=null;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session,HttpServletResponse response) throws IOException {
        //删除session对象中的user对象
        session.removeAttribute("user");

        response.sendRedirect("/vrd/home.html");
    }
}
